package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.News;
import cn.huhst.cas.weisiqian.service.NewsService;
import cn.huhst.cas.weisiqian.util.JSON;

@WebServlet("/AddNews.do")
public class AddNews extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(AddNews.class);
	private NewsService newsservice = null;

	public AddNews() {
		super();
		newsservice = new NewsService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String author = (String) session.getAttribute("username");
		News news = new News();
		news.setTitle(title);
		news.setContent(content);
		news.setAuthor(author);
		news.setWritetime(new java.sql.Date(new java.util.Date().getTime()));
		
		JSON json = news.checkFormat();
		if(json.isEmpty()){
			boolean result = newsservice.addNews(news);
			if(result){
				json.putOKMSG("发布新闻成功");
				logger.info("发布新闻成功");
			}else{
				json.putErrorMSG("发布新闻失败");
				logger.error("发布新闻失败");
			}
		}else{
			json.putErrorMSG("新闻格式不符合要求");
			logger.error("新闻格式不符合要求");
		}
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
